const { pool } = require('../config/database');
const logger = require('../utils/logger');

class RoleMenuModel {
  // 为角色分配菜单
  async assignMenus(roleId, menuIds) {
    try {
      // 开启事务
      const connection = await pool.getConnection();
      await connection.beginTransaction();
      
      try {
        // 1. 删除该角色的所有菜单关联
        await connection.execute(
          'DELETE FROM role_menus WHERE role_id = ?',
          [roleId]
        );
        
        // 2. 如果有新的菜单ID，则批量插入
        if (menuIds && menuIds.length > 0) {
          // 构建批量插入的值
          const values = menuIds.map(menuId => `(${roleId}, ${menuId})`).join(',');
          
          // 执行批量插入
          await connection.execute(
            `INSERT INTO role_menus (role_id, menu_id) VALUES ${values}`
          );
        }
        
        // 提交事务
        await connection.commit();
        return true;
      } catch (error) {
        // 回滚事务
        await connection.rollback();
        throw error;
      } finally {
        // 释放连接
        connection.release();
      }
    } catch (error) {
      logger.error('为角色分配菜单失败:', error);
      throw error;
    }
  }

  // 获取角色的菜单ID列表
  async getRoleMenuIds(roleId) {
    try {
      const [rows] = await pool.execute(
        'SELECT menu_id FROM role_menus WHERE role_id = ?',
        [roleId]
      );
      
      return rows.map(row => row.menu_id);
    } catch (error) {
      logger.error('获取角色菜单ID列表失败:', error);
      throw error;
    }
  }

  // 检查角色是否有特定菜单权限
  async hasMenuPermission(roleId, menuId) {
    try {
      const [rows] = await pool.execute(
        'SELECT 1 FROM role_menus WHERE role_id = ? AND menu_id = ?',
        [roleId, menuId]
      );
      
      return rows.length > 0;
    } catch (error) {
      logger.error('检查角色菜单权限失败:', error);
      throw error;
    }
  }
}

module.exports = new RoleMenuModel(); 